package com.hh.workorder.service;

import com.hh.workorder.entity.UserRoles;
import com.hh.workorder.repository.RoleRepository;
import com.hh.workorder.repository.UserRepository;
import com.hh.workorder.repository.UserRolesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final UserRolesRepository userRolesRepository;

    @Autowired
    public UserService(UserRepository userRepository, RoleRepository roleRepository, UserRolesRepository userRolesRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.userRolesRepository = userRolesRepository;
    }

    public void assignRolesToUser(int userId, List<Integer> roleIds) {
        // 检查用户是否存在
        if (!userRepository.existsById(userId)) {
            throw new IllegalArgumentException("User not found");
        }

        // 检查角色是否存在
        for (int roleId : roleIds) {
            if (!roleRepository.existsById(roleId)) {
                throw new IllegalArgumentException("Role not found");
            }
        }

        // 为用户分配角色
        for (int roleId : roleIds) {
            UserRoles userRoles = new UserRoles();
            userRoles.setUserId(userId);
            userRoles.setRoleId(roleId);
            userRolesRepository.save(userRoles);
        }
    }
}
